"use server"
import {BACKEND_BASE_URL} from '@/config/default'
import {NextRequest, NextResponse} from 'next/server'
import {setAuthTokens} from "@/lib/auth";

const BACKEND_LOGIN_URL = `${BACKEND_BASE_URL}/auth/login`


export async function POST(request: NextRequest) {
    const requestData = await request.json()
    const jsonData = JSON.stringify(requestData)
    const requestOptions = {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: jsonData
    }
    const response = await fetch(BACKEND_LOGIN_URL, requestOptions)
    const responseData = await response.json()
    if (response.ok) {
        // console.log("login/route.tsx:responseData", responseData)
        const {access_token, refresh_token, username} = responseData
        await setAuthTokens({access_token, refresh_token});
        return NextResponse.json({"loggedIn": true, "username": username}, {status: 200})
    }
    return NextResponse.json({"loggedIn": false, ...responseData}, {status: 400})
}